package com.andy.qi.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.andy.qi.domain.room.Room;
import com.andy.qi.domain.room.Seat;

@Service
public class UserMgr {
    
    @Autowired RoomMgr roomMgr;
    Map<String, SocketClient> userList = new HashMap<>();
    int userOnline = 0;
    
    public void bind(String userId, SocketClient socket){
        userList.put(userId, socket);
        userOnline++;
    }

    public void del(String userId){
        userList.remove(userId);
        userOnline--;
    }

    public SocketClient get(String userId){
        return userList.get(userId);
    }

    public boolean isOnline(String userId){
        SocketClient data = userList.get(userId);
        if(data != null){
            return true;
        }
        return false;
    }

    public int getOnlineCount(){
        return userOnline;
    }

    public void sendMsg(String userId,String event, Object msgdata){
        SocketClient socket = userList.get(userId);
        if(socket == null){
            return;
        }
        socket.emit(event, msgdata);
    }

    public void kickAllInRoom(String roomId){
        if(roomId == null){
            return;
        }
        Room roomInfo = roomMgr.getRoom(roomId);
        if(roomInfo == null){
            return;
        }

        for(int i = 0; i < roomInfo.seats.length; ++i){
            Seat rs = roomInfo.seats[i];

            //如果不需要发给发送方，则跳过
            if(rs.userId != null){
                SocketClient socket = userList.get(rs.userId);
                if(socket != null){
                    del(rs.userId);
                    socket.disconnect();
                }
            }
        }
    }

    public void broacastInRoom(String event,Object data, String sender, boolean includingSender){
        String roomId = roomMgr.getUserRoom(sender);
        if(roomId == null){
            return;
        }
        Room roomInfo = roomMgr.getRoom(roomId);
        if(roomInfo == null){
            return;
        }

        for(int i = 0; i < roomInfo.seats.length; ++i){
            Seat rs = roomInfo.seats[i];

            //如果不需要发给发送方，则跳过
            if(rs.userId == sender && includingSender != true){
                continue;
            }
            SocketClient socket = userList.get(rs.userId);
            if(socket != null){
                socket.emit(event,data);
            }
        }
    }
}
